// dh-consultations 云对象 - 在线问诊管理
const db = uniCloud.database();
const _ = db.command;
const { autoMountHospitalId, softDelete, batchSoftDelete, getUserById, getUserList } = require('dh-common');

/**
 * 统一响应格式化辅助函数
 */
function formatResponse(code, data = null, message = 'success', extraFields = {}) {
	return {
		code,
		data,
		message,
		success: (code === 200 || code === 201),
		timestamp: Date.now(),
		...extraFields
	};
}

/**
 * 统一错误响应辅助函数
 */
function formatError(error, defaultMessage = '操作失败') {
	console.error('[dh-consultations] 错误:', error);
	return {
		code: 500,
		message: error.message || defaultMessage,
		success: false,
		timestamp: Date.now()
	};
}

/**
 * 将职称等级转换为中文文本
 */
function getTitleText(titleLevel) {
	const titleMap = {
		0: '住院医师',
		1: '主治医师',
		2: '副主任医师',
		3: '主任医师',
		4: '知名专家'
	};
	return titleMap[titleLevel] || '医师';
}

/**
 * 为单个问诊记录附加医生和患者信息
 */
async function enrichConsultationInfo(consultation) {
	if (!consultation) return consultation;

	// 获取医生信息
	if (consultation.doctor_id) {
		try {
			const doctorRes = await db.collection('dh-doctors')
				.doc(consultation.doctor_id)
				.field({ user_id: true, title_level: true })
				.get();

			if (doctorRes.data.length > 0) {
				const doctor = doctorRes.data[0];
				
				// 获取医生的真实姓名（使用统一的用户查询工具）
				if (doctor.user_id) {
					const userInfo = await getUserById(doctor.user_id, 'default', false, true);
					if (userInfo) {
						const realName = userInfo.realName || userInfo.displayName || '未知';
						consultation.doctor_name = realName;
						consultation.doctor_title = getTitleText(doctor.title_level);
						consultation.doctor_title_level = doctor.title_level;
					}
				}
			}
		} catch (error) {
			console.error('[dh-consultations] 获取医生信息失败:', error);
			consultation.doctor_name = '暂无';
			consultation.doctor_title = '';
		}
	}

	// 获取患者信息（使用统一的用户查询工具）
	if (consultation.patient_id) {
		try {
			const userInfo = await getUserById(consultation.patient_id, 'default', true, true);
			if (userInfo) {
				consultation.patient_name = userInfo.realName || userInfo.displayName || '未知';
			}
		} catch (error) {
			console.error('[dh-consultations] 获取患者信息失败:', error);
			consultation.patient_name = '暂无';
		}
	}

	return consultation;
}

/**
 * 为问诊列表批量附加医生和患者信息
 */
async function enrichConsultationsList(consultations) {
	if (!Array.isArray(consultations) || consultations.length === 0) {
		return consultations;
	}

	// 收集所有医生ID和患者ID
	const doctorIds = [...new Set(consultations.map(c => c.doctor_id).filter(Boolean))];
	const patientIds = [...new Set(consultations.map(c => c.patient_id).filter(Boolean))];

	// 批量获取医生信息
	const doctorMap = {};
	if (doctorIds.length > 0) {
		try {
			const doctorRes = await db.collection('dh-doctors')
				.where({ _id: _.in(doctorIds) })
				.field({ _id: true, user_id: true, title_level: true })
				.get();

			// 获取医生对应的用户信息（使用统一的用户查询工具）
			const doctorUserIds = doctorRes.data.map(d => d.user_id).filter(Boolean);
			const userMap = {};
			
			if (doctorUserIds.length > 0) {
				// 使用 getUserList 批量查询医生信息
				const allDoctors = await getUserList({
					includeRoles: ['doctor'],
					format: 'default',
					limit: 1000,
					decryptSensitiveInfo: true
				});
				
				// 构建用户ID到姓名的映射
				allDoctors.forEach(user => {
					if (doctorUserIds.includes(user._id)) {
						userMap[user._id] = user.realName || user.displayName || '未知';
					}
				});
			}

			// 构建医生映射
			doctorRes.data.forEach(doctor => {
				doctorMap[doctor._id] = {
					name: userMap[doctor.user_id] || '暂无',
					title: getTitleText(doctor.title_level),
					title_level: doctor.title_level
				};
			});
		} catch (error) {
			console.error('[dh-consultations] 批量获取医生信息失败:', error);
		}
	}

	// 批量获取患者信息（使用统一的用户查询工具）
	const patientMap = {};
	if (patientIds.length > 0) {
		try {
			// 使用 getUserList 批量查询患者信息
			const allPatients = await getUserList({
				includeRoles: ['patient'],
				allowPatients: true,
				format: 'default',
				limit: 1000,
				decryptSensitiveInfo: true
			});
			
			// 构建患者ID到姓名的映射
			allPatients.forEach(patient => {
				if (patientIds.includes(patient._id)) {
					patientMap[patient._id] = patient.realName || patient.displayName || '未知';
				}
			});
		} catch (error) {
			console.error('[dh-consultations] 批量获取患者信息失败:', error);
		}
	}

	// 附加信息到问诊记录
	consultations.forEach(consultation => {
		if (consultation.doctor_id && doctorMap[consultation.doctor_id]) {
			consultation.doctor_name = doctorMap[consultation.doctor_id].name;
			consultation.doctor_title = doctorMap[consultation.doctor_id].title;
			consultation.doctor_title_level = doctorMap[consultation.doctor_id].title_level;
		} else {
			consultation.doctor_name = '暂无';
			consultation.doctor_title = '';
		}

		if (consultation.patient_id && patientMap[consultation.patient_id]) {
			consultation.patient_name = patientMap[consultation.patient_id];
		} else {
			consultation.patient_name = '暂无';
		}
	});

	return consultations;
}

module.exports = {
	/**
	 * 请求前拦截
	 */
	async _before(methodName, params) {
		const uniIdToken = this.getUniIdToken();
		console.log(`[dh-consultations] 调用方法: ${methodName}, 用户ID: ${uniIdToken?.uid}`);

		const writeMethods = ['create', 'update', 'delete', 'batch', 'complete', 'cancel'];
		if (methodName && writeMethods.some(method => methodName.toLowerCase().includes(method))) {
			if (!uniIdToken || !uniIdToken.uid) {
				throw new Error('401|未授权的访问');
			}
		}

		if (params && typeof params === 'object') {
			for (let key in params) {
				if (typeof params[key] === 'string') {
					params[key] = params[key].trim();
				}
			}
		}
	},

	/**
	 * 根据ID查询问诊
	 */
	async getConsultationById(id) {
		try {
			if (!id) {
				return formatResponse(400, null, '问诊ID不能为空');
			}

			const res = await db.collection('dh-consultations').doc(id).get();
			if (res.data.length === 0) {
				return formatResponse(404, null, '问诊不存在');
			}
			
			// 附加医生和患者信息
			const enrichedData = await enrichConsultationInfo(res.data[0]);
			return formatResponse(200, enrichedData);
		} catch (error) {
			return formatError(error, '获取问诊失败');
		}
	},

	/**
	 * 获取问诊列表（自动关联医生和患者信息）
	 */
	async listConsultations(query = {}, skip = 0, limit = 20) {
		try {
			if (typeof query !== 'object' || query === null || Array.isArray(query)) {
				query = {};
			}
			skip = parseInt(skip) || 0;
			limit = parseInt(limit) || 20;
			
			// 默认不显示已删除记录
			query.is_deleted = false;
			
			const res = await db.collection('dh-consultations')
				.where(query)
				.skip(skip)
				.limit(limit)
				.orderBy('create_time', 'desc')
				.get();
			
			// 批量附加医生和患者信息
			const enrichedData = await enrichConsultationsList(res.data);
			
			return formatResponse(200, enrichedData, 'success', { count: enrichedData.length });
		} catch (error) {
			return formatError(error, '获取问诊列表失败');
		}
	},

	/**
	 * 创建问诊
	 */
	async createConsultation(data) {
		try {
			if (!data.patient_id || !data.doctor_id) {
				return formatResponse(400, null, '患者和医生ID不能为空');
			}

		let consultationData = {
			patient_id: data.patient_id,
			patient_name: data.patient_name || '',
			doctor_id: data.doctor_id,
			doctor_name: data.doctor_name || '',
				type: data.type || 'text',
				title: data.title || '',
				description: data.description || '',
				status: data.status || 'pending',
				priority: data.priority || 'normal',
				images: data.images || [],
				messages: [],
				consultation_fee: data.consultation_fee || 0,
				paid: data.paid !== undefined ? data.paid : false,
				accepted_at: null,
				completed_at: null,
				notes: data.notes || '',
				is_deleted: false,  // 软删除字段，默认未删除
			create_time: Date.now(),
			update_time: Date.now()
		};

		// 🏥 自动挂载医院ID（单一医院系统特性）
		consultationData = await autoMountHospitalId(consultationData);

		const res = await db.collection('dh-consultations').add(consultationData);
			return formatResponse(201, { _id: res.id }, '问诊创建成功');
		} catch (error) {
			return formatError(error, '创建问诊失败');
		}
	},

	/**
	 * 更新问诊信息
	 */
	async updateConsultation(id, data) {
		try {
			if (!id) {
				return formatResponse(400, null, '问诊ID不能为空');
			}

			const updateData = {
				...data,
				update_time: Date.now()
			};

			await db.collection('dh-consultations').doc(id).update(updateData);
			return formatResponse(200, null, '问诊信息更新成功');
		} catch (error) {
			return formatError(error, '更新问诊失败');
		}
	},

	/**
	 * 删除问诊
	 */
	async deleteConsultation(id, reason = '') {
		try {
			if (!id) {
				return formatResponse(400, null, '问诊ID不能为空');
			}

			const uniIdToken = this.getUniIdToken();
			const result = await softDelete('dh-consultations', id, uniIdToken?.uid || '', reason);
			
			if (result.code === 200) {
				return formatResponse(200, null, '问诊已移至回收站');
			} else {
				return formatResponse(result.code, null, result.message);
			}
		} catch (error) {
			return formatError(error, '删除问诊失败');
		}
	},

	/**
	 * 批量更新问诊
	 */
	async batchUpdateConsultations(updates) {
		try {
			if (!Array.isArray(updates) || updates.length === 0) {
				return formatResponse(400, null, '更新数据不能为空');
			}

			const promises = updates.map(item =>
				db.collection('dh-consultations').doc(item._id).update({
					...item,
					update_time: Date.now()
				})
			);

			await Promise.all(promises);
			return formatResponse(200, null, `批量更新${updates.length}条记录成功`);
		} catch (error) {
			return formatError(error, '批量更新失败');
		}
	},

	/**
	 * 批量删除问诊
	 */
	async batchDeleteConsultations(ids, reason = '') {
		try {
			if (!Array.isArray(ids) || ids.length === 0) {
				return formatResponse(400, null, 'ID列表不能为空');
			}

			const uniIdToken = this.getUniIdToken();
			const result = await batchSoftDelete('dh-consultations', ids, uniIdToken?.uid || '', reason);
			
			return formatResponse(result.code, result.data, result.message);
		} catch (error) {
			return formatError(error, '批量删除失败');
		}
	},

	/**
	 * 医生接受问诊
	 */
	async acceptConsultation(id) {
		try {
			if (!id) {
				return formatResponse(400, null, '问诊ID不能为空');
			}

			await db.collection('dh-consultations').doc(id).update({
				status: 'in_progress',
				accepted_at: Date.now(),
				update_time: Date.now()
			});

			return formatResponse(200, null, '问诊已接受');
		} catch (error) {
			return formatError(error, '接受问诊失败');
		}
	},

	/**
	 * 完成问诊
	 */
	async completeConsultation(id) {
		try {
			if (!id) {
				return formatResponse(400, null, '问诊ID不能为空');
			}

			await db.collection('dh-consultations').doc(id).update({
				status: 'completed',
				completed_at: Date.now(),
				update_time: Date.now()
			});

			return formatResponse(200, null, '问诊已完成');
		} catch (error) {
			return formatError(error, '完成问诊失败');
		}
	},

	/**
	 * 取消问诊
	 */
	async cancelConsultation(id, reason) {
		try {
			if (!id) {
				return formatResponse(400, null, '问诊ID不能为空');
			}

			await db.collection('dh-consultations').doc(id).update({
				status: 'cancelled',
				notes: reason || '',
				update_time: Date.now()
			});

			return formatResponse(200, null, '问诊已取消');
		} catch (error) {
			return formatError(error, '取消问诊失败');
		}
	}
};
